'use strict';

angular.module('com.dcos.app').controller('TemplateDetailController', function($rootScope,$window,$scope,$state,$stateParams, $filter, api, $uibModal, TemplateDetailService) {
  
  var vm = this;
  
  vm.breadCrumbArr = [api.breadCrumbMap.templatemanage.root,api.breadCrumbMap.templatemanage.detail.root];

  $scope.propertydata=[];

  $scope.formdata = {};

  $scope.curProjectId=$window.sessionStorage.getItem("curProjectId");

  vm.userid=$window.sessionStorage.getItem("curUserId");

  vm.flowdata={};

  // if(!vm.userid)
  //   $state.go('login');

  $scope.pipeline=false;

  vm.menudata=[];
  $scope.curNodeId="";
  $scope.flowdata={};

  var t_id=$stateParams.t_id;
  
  if(!t_id)
    t_id='';

  function fnInit() {
    TemplateDetailService.init(t_id).then(function (response) {
      vm.flowdata=response.data.flowdata;
      vm.menudata=response.data.menudata;
      angular.forEach(vm.menudata,function(item,index){
        angular.forEach(item.plugin,function(_item,_index){
          $scope.propertydata.push(_item);
        });
      });
      $scope.flowdata=response.data.flowdata;
      $scope.fnInitData();
    });
    
  }
  fnInit();

  $scope.fnSave = function (data) {
    if(!vm.flowdata.t_id){
        var modalInstance = $uibModal.open({
          animation: true,
          templateUrl: 'controllers/workflow/create/template/create.html',
          controller: 'TemplateNameController as vm',
          resolve: {
            save:function(){return vm.fnSaveTemplate;},
            savedata:function(){return data;},
            templateName:function(){return data.t_name;}
          }
        });
    }
    else{
      data.t_id=vm.flowdata.t_id;
      data.t_name=vm.flowdata.t_name;
      vm.fnSaveTemplate(data);
    }
  }
  vm.fnSaveTemplate = function (data) {
    $rootScope.loading = true;
    TemplateDetailService.save(data).then(function (response) {
        $rootScope.loading = false;
        $state.go('app.templatemanage', {}, { reload: true });
    });
  }

});

